<template>
  <RenameDialog
    v-if="renameDialogVisible"
    :visible.sync="renameDialogVisible"
    :file="explorer.currentRow"
    :name-prop="explorer.nameProp"
    @rename-success="renameSuccess" />
</template>

<script>
  import RenameDialog from '@/components/x-file-explorer-lite/plugins/RenameDialog'
  import { getFilePrefix } from '@web-utils/core'

  export default {
    name: 'RenameFilePlugin',
    components: { RenameDialog },
    inject: ['explorer'],
    data() {
      return {
        renameDialogVisible: false
      }
    },
    methods: {
      async rename() {
        const { explorer } = this
        if (explorer.nameEditMode === 'inline') {
          if (explorer.currentRow.type === 'directory') {
            explorer.fileName = explorer.currentRow[explorer.nameProp]
          } else {
            explorer.fileName = getFilePrefix(explorer.currentRow[explorer.nameProp])
          }
          explorer.editFile(explorer.currentRow)
          await explorer.$nextTick()
          explorer.$refs.etName.$refs.input.focus()
          explorer.$refs.etName.$refs.input.setSelectionRange(0, explorer.currentRow[explorer.nameProp].length)
        } else {
          this.renameDialogVisible = true
        }
      },
      renameSuccess(newName) {
        const { explorer } = this
        explorer.currentRow[explorer.nameProp] = newName
        if (explorer.currentRow.fileType === 'folder' && explorer.$refs.tree) {
          const nodes = explorer.$refs.tree.$refs.etTree.findTreeNode(explorer.currentRow.id)
          nodes.forEach(node => {
            node.data[explorer.nameProp] = explorer.currentRow[explorer.nameProp]
          })
        }
      }
    }
  }
</script>
